
// MCANpLogAnalyserDlg.cpp : implementation file
//

#include "stdafx.h"
#include "MCANpLogAnalyser.h"
#include "MCANpLogAnalyserDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif



// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CMCANpLogAnalyserDlg dialog




CMCANpLogAnalyserDlg::CMCANpLogAnalyserDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CMCANpLogAnalyserDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CMCANpLogAnalyserDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CMCANpLogAnalyserDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTON_DRAW_DISTRIBUTION, &CMCANpLogAnalyserDlg::OnBnClickedButtonDrawDistribution)
	ON_BN_CLICKED(IDC_BUTTON_ANALYSIS_RESULT, &CMCANpLogAnalyserDlg::OnBnClickedButtonAnalysisRangeQueryResult)
	ON_BN_CLICKED(IDC_BUTTON_ANALYSIS_KNN_RESULT, &CMCANpLogAnalyserDlg::OnBnClickedButtonAnalysisKnnResult)
END_MESSAGE_MAP()


// CMCANpLogAnalyserDlg message handlers

BOOL CMCANpLogAnalyserDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CMCANpLogAnalyserDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CMCANpLogAnalyserDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CMCANpLogAnalyserDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CMCANpLogAnalyserDlg::OnBnClickedButtonDrawDistribution()
{
	// TODO: Add your control notification handler code here
	CFileDialog cFile(TRUE,""," ",6,"Text Files (*.txt)|*.txt||");
	if(cFile.DoModal()==IDOK)
	{
		CString strPath (cFile.GetPathName());
		strPath = strPath.Left(strPath.GetLength()-cFile.GetFileName().GetLength());
		ifstream fin(cFile.GetPathName().GetString());
		if(fin)
		{
			
			int nTime = 0;
			CRawData cRawData;
			while(fin>>nTime)
			{
				CCalculator cCal;
				for(int i = 0;i<100;i++)
				{
					int nAmount = 0;
					fin>>nAmount;
					cCal.Add(nAmount);
				}
				cCal.Calculate();
				cRawData.Add(nTime,cCal.GetEven(),cCal.GetMax(),cCal.GetMin(),cCal.GetSDev());
			}
			this->Draw(cRawData,Both,"Data Object Distribution","Time(M)","Local Data Number",strPath);
		}
		else
		{
			this->MessageBox("open file error");
		}
	}
}
int CMCANpLogAnalyserDlg::Draw(const CRawData& cRawData, const PLOT_TYPE nType, const CString & strName, const CString & strX,const CString & strY,const CString & strOutputPath)
{
	this->UpdateData();
	CString strScriptNamePath(strOutputPath);
	if(strScriptNamePath[strScriptNamePath.GetLength()-1]!='\\')
	{
		strScriptNamePath.AppendChar('\\');
	}
	CString strRawDataNamePath(strScriptNamePath);
	CString strFigureNamePath(strScriptNamePath);
	
	CString strFileName;
	for(int i = 0;i<strName.GetLength();++i)
	{
		char c = strName[i];
		if((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c>='0'&&c<='9'))
		{
			strFileName.AppendChar(c);
		}
	}
	switch(nType)
	{
		
		case StdDevi:
		{
			strScriptNamePath.AppendFormat("%s_%s.plt",strFileName.GetString(),"SD");
			strRawDataNamePath.AppendFormat("%s_%s.dat",strFileName.GetString(),"SD");
			strFigureNamePath.AppendFormat("%s_%s.eps",strFileName.GetString(),"SD");
		}
		break;
		case MaxMin:
		{
			strScriptNamePath.AppendFormat("%s_%s.plt",strFileName.GetString(),"MaxMin");
			strRawDataNamePath.AppendFormat("%s_%s.dat",strFileName.GetString(),"MaxMin");
			strFigureNamePath.AppendFormat("%s_%s.eps",strFileName.GetString(),"MaxMin");
		}
		break;
		case Both:
		{
			strScriptNamePath.AppendFormat("%s_%s.plt",strFileName.GetString(),"Both");
			strRawDataNamePath.AppendFormat("%s_%s.dat",strFileName.GetString(),"Both");
			strFigureNamePath.AppendFormat("%s_%s.eps",strFileName.GetString(),"Both");
		}
		break;
		default:
		{
			strScriptNamePath.AppendFormat("%s_%s.plt",strFileName.GetString(),"Mean");
			strRawDataNamePath.AppendFormat("%s_%s.dat",strFileName.GetString(),"Mean");
			strFigureNamePath.AppendFormat("%s_%s.eps",strFileName.GetString(),"Mean");
		}
		break;
	}
	ofstream fout(strRawDataNamePath.GetString());
	if(fout)
	{
		for (unsigned i = 0;i<cRawData.size();i++)
		{
			fout<<cRawData.ToString(i).GetString()<<endl;	
		}
		fout.close();
	}
	else
	{
		this->MessageBox("Create Data File Error!");
		return 1;
	}
	CString script("reset \n");
	if(nType==Both)
	{
		script.AppendFormat("set term postscript eps color enhanced \n");
		script.AppendFormat("set output '%s'\n",strFigureNamePath.GetString());
		script.AppendFormat("unset key \n");
		script.AppendFormat("set multiplot\n");
		script.AppendFormat("set size 0.4,0.6\n");
		script.AppendFormat("set origin 0.1,0.1\n");
		script.AppendFormat("set title '(a) SD error bar'\n");
		script.AppendFormat("set xlabel '%s' \n",strX.GetString());
		script.AppendFormat("set ylabel '%s'\n",strY.GetString());
		script.AppendFormat("set yrange [0:65]\n");
		script.AppendFormat("plot '%s' using 1:2:5:6   with yerrorbars lt 1 lw 1 ,",strRawDataNamePath.GetString());
		script.AppendFormat("'%s' using 1:2   with line lt 1 lw 2 \n",strRawDataNamePath.GetString());
				
		script.AppendFormat("set size 0.4,0.6\n");
		script.AppendFormat("set origin 0.5,0.1\n");
		script.AppendFormat("set title '(b) Max-Min error bar'\n");
		script.AppendFormat("set xlabel '%s' \n",strX.GetString());
		script.AppendFormat("set ylabel '%s'\n",strY.GetString());
		script.AppendFormat("set yrange [0:65]\n");
		script.AppendFormat("plot '%s' using 1:2:3:4   with yerrorbars lt 1 lw 1 ,",strRawDataNamePath.GetString());
		script.AppendFormat("'%s' using 1:2   with line lt 1 lw 2 \n",strRawDataNamePath.GetString());
				
		script.AppendFormat("unset multiplot\n");


		script.AppendFormat("reset \n");
		script.AppendFormat("set term windows\n");

		script.AppendFormat("unset key \n");
		script.AppendFormat("set multiplot\n");
		script.AppendFormat("set size 0.4,0.6\n");
		script.AppendFormat("set origin 0.1,0.1\n");
		script.AppendFormat("set title '(a) SD error bar'\n");
		
		script.AppendFormat("set xlabel '%s' \n",strX.GetString());
		script.AppendFormat("set ylabel '%s'\n",strY.GetString());
		script.AppendFormat("set yrange [0:65]\n");

		script.AppendFormat("plot '%s' using 1:2:5:6   with yerrorbars lt 1 lw 1 ,",strRawDataNamePath.GetString());
		script.AppendFormat("'%s' using 1:2   with line lt 1 lw 2 \n",strRawDataNamePath.GetString());
				
		script.AppendFormat("set size 0.4,0.6\n");
		script.AppendFormat("set origin 0.5,0.1\n");
		script.AppendFormat("set title '(b) Max-Min error bar'\n");
		script.AppendFormat("set xlabel '%s' \n",strX.GetString());
		script.AppendFormat("set ylabel '%s'\n",strY.GetString());
		script.AppendFormat("set yrange [0:65]\n");

		script.AppendFormat("plot '%s' using 1:2:3:4   with yerrorbars lt 1 lw 1 ,",strRawDataNamePath.GetString());
		script.AppendFormat("'%s' using 1:2   with line lt 1 lw 2 \n",strRawDataNamePath.GetString());
		
		script.AppendFormat("unset multiplot\n");
		script.AppendFormat("reset \n");
	}
	else
	{
		script.AppendFormat("set term postscript eps color enhanced \n");
		script.AppendFormat("set title '%s'\n",strName.GetString());
		script.AppendFormat("set output '%s'\n",strFigureNamePath.GetString());
		script.AppendFormat("unset key \n");
		script.AppendFormat("set xlabel '%s' \n",strX.GetString());
		script.AppendFormat("set ylabel '%s'\n",strY.GetString());
		switch(nType)
		{
			case StdDevi:
			{
				script.AppendFormat("plot '%s' using 1:2:5:6   with yerrorbars lt 1 lw 1 ,",strRawDataNamePath.GetString());
				script.AppendFormat("'%s' using 1:2   with line lt 1 lw 2 \n",strRawDataNamePath.GetString());
				break;
			}
			case MaxMin:
			{
				script.AppendFormat("plot '%s' using 1:2:3:4   with yerrorbars lt 1 lw 1 ,",strRawDataNamePath.GetString());
				script.AppendFormat("'%s' using 1:2   with line lt 1 lw 2 \n",strRawDataNamePath.GetString());
				break;
			}
			default:
			{
				script.AppendFormat("plot '%s' using 1:2   with linespoints lt 1 lw 2 \n",strRawDataNamePath.GetString());
				break;
			}
		}
		script.AppendFormat("set term windows\n");
		script.AppendFormat("replot\n");
	}
	FILE *pFile ;
	if(0==fopen_s(&pFile,strScriptNamePath.GetString(),"w"))
	{
		fwrite(script.GetBuffer(),1,script.GetLength(),pFile);
		fclose(pFile);
		CString cmd;
		cmd.Format("pgnuplot.exe -persist \"%s\"",strScriptNamePath.GetString());
		WinExec(cmd.GetString(),SW_SHOW);
	}
	else
	{
		MessageBox("Open File Error!");
		return 2;
	}
	return 0;
}
void CMCANpLogAnalyserDlg::OnBnClickedButtonAnalysisRangeQueryResult()
{
	CFileDialog cFile(TRUE,""," ",6,"Text Files (*.txt)|*.txt||");
	if(cFile.DoModal()==IDOK)
	{
		CString strPath (cFile.GetPathName());
		strPath = strPath.Left(strPath.GetLength()-cFile.GetFileName().GetLength());
		ifstream fin(cFile.GetPathName().GetString());
		map<int,CRawData> cNodeVisitDataMap,cDataVisitDataMap;
		class CReg:
			public CAtlRegExp<> 
		{
		} cReg;
		
		REParseError status = cReg.Parse("Search Round: {(\\d+)} Network Size: {(\\d+)}");
		if(REPARSE_ERROR_OK == status&&fin)
		{
			char buf[1024];
			while(fin.getline(buf,1024))
			{
				int nTime = 0;
				CAtlREMatchContext<> cMatchContext;
				if (!cReg.Match(buf,&cMatchContext))
				{
					continue;
				}
				if(2!=cMatchContext.m_uNumGroups)
				{
					continue;
				}				
				else
				{
					char Number[32];
					const CAtlREMatchContext<>::RECHAR* szStart = 0;
					const CAtlREMatchContext<>::RECHAR* szEnd = 0;
					cMatchContext.GetMatch(0, &szStart, &szEnd);
					ptrdiff_t nLength = szEnd - szStart;
					sprintf_s(Number,32,"%.*s", nLength, szStart);
					nTime = atoi(Number);;
					int nRadius = 0; double dNodeVisit,dDataVisit,dDepth,dHitRatio;
					for(int i = 0;i<20;i++)
					{

						fin>>nRadius>>dNodeVisit>>dDataVisit>>dDepth>>dHitRatio;
						if(nRadius>220)
							continue;
						map<int,CRawData>::iterator it =cNodeVisitDataMap.find(nRadius);
						if(it==cNodeVisitDataMap.end())
						{
							it=cNodeVisitDataMap.insert(make_pair(nRadius,CRawData())).first;
						}
						it->second.Add(nTime+10,dNodeVisit,0,0,0);
						 it =cDataVisitDataMap.find(nRadius);
						if(it==cDataVisitDataMap.end())
						{
							it=cDataVisitDataMap.insert(make_pair(nRadius,CRawData())).first;
						}
						it->second.Add(nTime+10,dDataVisit,0,0,0);
					}
				}
			}
			this->Draw3D(	cNodeVisitDataMap,"Range Query Node Visit Ratio","Time(M)","Search Radius","",strPath);
			if(this->MessageBox("Next?","^O^",MB_YESNO)==IDYES)
			{
				this->Draw3D(	cDataVisitDataMap,"Range Query Data Visit Ratio","Time(M)","Search Radius","",strPath);
			}
		}
		else
		{
			this->MessageBox("open file error");
		}
	}
}

void CMCANpLogAnalyserDlg::Draw3D(map<int,CRawData> & cData, const CString & strTitle,const CString & strX,const CString & strY,const CString & strZ, const CString & strOutputPath)
{
	CString strScriptNamePath(strOutputPath);
	this->UpdateData();
	if(strScriptNamePath[strScriptNamePath.GetLength()-1]!='\\')
	{
		strScriptNamePath.AppendChar('\\');
	}
	CString strRawDataNamePath(strScriptNamePath);
	CString strFigureNamePath(strScriptNamePath);
	CString strFileName;
	for(int i = 0;i<strTitle.GetLength();++i)
	{
		char c = strTitle[i];
		if((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c>='0'&&c<='9'))
		{
			strFileName.AppendChar(c);
		}
	}
	strScriptNamePath.AppendFormat("%s_%s.plt",strFileName.GetString(),"3D");
	strRawDataNamePath.AppendFormat("%s_%s.dat",strFileName.GetString(),"3D");
	strFigureNamePath.AppendFormat("%s_%s.eps",strFileName.GetString(),"3D");
	ofstream fout(strRawDataNamePath.GetString());
	if(fout)
	{
		unsigned nSize = cData.begin()->second.size();
		for(map<int,CRawData>::iterator it = cData.begin();it!=cData.end();++it)
		{
			nSize = min(nSize,it->second.size());
		}
		for(unsigned i = 0;i<nSize;i++)
		{
			for(map<int,CRawData>::iterator it = cData.begin();it!=cData.end();++it)
			{
				fout<<it->second[i][0]<<" "<<(it->second[i][1])<<" "<<it->first<<" ";
			}
			fout<<endl;
		}
		fout.close();
	}
	else
	{
		this->MessageBox("Create Data File Error!");
		return ;
	}
	CString script("reset \n");
	script.AppendFormat("set term postscript eps color enhanced \n");
	script.AppendFormat("set title '%s'\n",strTitle.GetString());
	script.AppendFormat("set output '%s'\n",strFigureNamePath.GetString());
	script.AppendFormat("unset key \nset ticslevel 0\n");
	script.AppendFormat("set xlabel '%s' \n",strX.GetString());
	script.AppendFormat("set ylabel '%s'\n",strY.GetString());
	script.AppendFormat("set zlabel '%s'\n",strZ.GetString());
	/*if(this->m_nMaxX!=0)
	{
		script.AppendFormat("set xrange [%d:%d] \n",m_nMinX,m_nMaxX);
	}
	if(m_strXAxis.GetLength()>1)
	{
		script.AppendFormat("set xtics (%s) \n",m_strXAxis.GetString());
	}
	if(m_nMaxY!=0)
	{
		script.AppendFormat("set yrange [%d:%d] \n",m_nMinY,m_nMaxY);
	}	
	if(m_strYAxis.GetLength()>1)
	{
		script.AppendFormat("set ytics (%s) \n",m_strYAxis.GetString());
	}
	if(m_nMaxZ!=0)
	{
		script.AppendFormat("set zrange [%d:%d] \n",m_nMinZ,m_nMaxZ);
	}	
	if(m_strZAxis.GetLength()>1)
	{
		script.AppendFormat("set ztics (%s) \n",m_strZAxis.GetString());
	}*/
	script.AppendFormat("set grid\n");
	script.AppendFormat("set view 38,315\n");
	script.Append("splot ");
	for(unsigned i = 0;i<cData.size();i++)
	{
		script.AppendFormat("'%s' using %u:%u:%u with linespoints  pointtype %u lt %u lw 2 , '%s' using %u:%u:%u with impulses  lt %u lw 1"
			,strRawDataNamePath.GetString(),i*3+1,i*3+3,i*3+2,i+1,i+1,strRawDataNamePath.GetString(),i*3+1,i*3+3,i*3+2,i+1);
	
		if(i!=cData.size()-1)
		{
			script.AppendChar(',');
		}
		else
		{
			script.AppendChar('\n');
		}
	}
	script.AppendFormat("set term windows\n");
	script.AppendFormat("replot\n");
	FILE *pFile ;
	if(0==fopen_s(&pFile,strScriptNamePath.GetString(),"w"))
	{
		fwrite(script.GetBuffer(),1,script.GetLength(),pFile);
		fclose(pFile);
		CString cmd;
		cmd.Format("pgnuplot.exe -persist \"%s\"",strScriptNamePath.GetString());
		WinExec(cmd.GetString(),SW_SHOW);
	}
	else
	{
		MessageBox("Open File Error!");
	}
	return;
}


void CMCANpLogAnalyserDlg::OnBnClickedButtonAnalysisKnnResult()
{
	CFileDialog cFile(TRUE,""," ",6,"Text Files (*.txt)|*.txt||");
	if(cFile.DoModal()==IDOK)
	{
		CString strPath (cFile.GetPathName());
		strPath = strPath.Left(strPath.GetLength()-cFile.GetFileName().GetLength());
		ifstream fin(cFile.GetPathName().GetString());
		map<int,CRawData> cNodeVisitDataMap,cDataVisitDataMap;
		class CReg:
			public CAtlRegExp<> 
		{
		} cReg;
		
		REParseError status = cReg.Parse("Search Round: {(\\d+)} Network Size: {(\\d+)}");
		if(REPARSE_ERROR_OK == status&&fin)
		{
			char buf[1024];
			while(fin.getline(buf,1024))
			{
				int nTime = 0;
				CAtlREMatchContext<> cMatchContext;
				if (!cReg.Match(buf,&cMatchContext))
				{
					continue;
				}
				if(2!=cMatchContext.m_uNumGroups)
				{
					continue;
				}				
				else
				{
					char Number[32];
					const CAtlREMatchContext<>::RECHAR* szStart = 0;
					const CAtlREMatchContext<>::RECHAR* szEnd = 0;
					cMatchContext.GetMatch(0, &szStart, &szEnd);
					ptrdiff_t nLength = szEnd - szStart;
					sprintf_s(Number,32,"%.*s", nLength, szStart);
					nTime = atoi(Number);;
					int nRadius = 0; double dNodeVisit,dDataVisit,dDepth;
					for(int i = 0;i<15;i++)
					{

						fin>>nRadius>>dNodeVisit>>dDataVisit>>dDepth;
						if(nRadius>80)
							continue;
						map<int,CRawData>::iterator it =cNodeVisitDataMap.find(nRadius);
						if(it==cNodeVisitDataMap.end())
						{
							it=cNodeVisitDataMap.insert(make_pair(nRadius,CRawData())).first;
						}
						it->second.Add(nTime+10,dNodeVisit,0,0,0);
						 it =cDataVisitDataMap.find(nRadius);
						if(it==cDataVisitDataMap.end())
						{
							it=cDataVisitDataMap.insert(make_pair(nRadius,CRawData())).first;
						}
						it->second.Add(nTime+10,dDataVisit,0,0,0);
					}
				}
			}
			this->Draw3D(	cNodeVisitDataMap,"kNN Node Visit Ratio","Time(M)","K ","",strPath);
			if(this->MessageBox("Next?","^O^",MB_YESNO)==IDYES)
			{
				this->Draw3D(	cDataVisitDataMap,"kNN Data Visit Ratio","Time(M)","K ","",strPath);
			}
		}
		else
		{
			this->MessageBox("open file error");
		}
	}
}

